package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.FollowBehaviorDto;
import com.heima.behavior.pojos.ApFollowBehavior;
import com.heima.behavior.service.ApFollowBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class ApFollowBehaviorServiceImpl implements ApFollowBehaviorService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 关注用户行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(FollowBehaviorDto dto) {

        //3.获取登录用户id
        ApUser apUser = ApThreadLocal.getApUser();
        if (apUser == null || apUser.getId() == 0) {//没有查询到用户，说明是非登录
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH, "此时是游客身份");
        }
        //1.参数判断
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //定义关注的key
        String followKey = "USER_FOLLOW_" + apUser.getId();
        //定义粉丝的key
        String fansKey = "USER_FANS_" + apUser.getId();
        /**
         *   查询的是redis的信息，key=USER_FOLLOW_{userId}
         *   hashKey(参数1，参数2)
         *   参数1表示redis的大key,参数2表示小key=作者id
         *   flag=true表示当前用户已经关注过该作者，否则没有关注
         */
        //2.用户是否已经关注
        Boolean flag = stringRedisTemplate.opsForHash().hasKey(followKey, dto.getAuthorId().toString());
        //如果用户已经关注了，并且此时要执行关注操作 operation=0，(关注)
        if (flag && dto.getOperation() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "该用户已经关注过该作者");
        }
        //如果用户已经关注了，并且此时要执行取消关注operation=1，删除mongo和redis
        if (flag && dto.getOperation() == 1) {
            //就执行删除redis
            stringRedisTemplate.opsForHash().delete(followKey, dto.getAuthorId().toString());
            stringRedisTemplate.opsForHash().delete(fansKey, apUser.getId().toString());
            //删除mongo
            /**
             *   删除mongo
             *   删除的逻辑：一个用户可以关注多个作者
             *   根据用户id和作者id一块删除
             */
            Query query = Query.query(Criteria.where("userId").is(apUser.getId()).and("followId").is(dto.getAuthorId()));
            mongoTemplate.remove(query, ApFollowBehavior.class);
        }
        //用户没有关注，并且此时执行的是关注操作 operation=0,新增数据到redis和mongo中
        if (flag && dto.getOperation() == 0) {
            //新增到redis
            stringRedisTemplate.opsForHash().put(followKey, dto.getAuthorId().toString(), "1");
            stringRedisTemplate.opsForHash().put(fansKey, apUser.getId().toString(), "1");
            //新增到mongo
            ApFollowBehavior apFollowBehavior = new ApFollowBehavior();
            apFollowBehavior.setFollowId(dto.getAuthorId());
            apFollowBehavior.setUserId(apUser.getId().longValue());
            apFollowBehavior.setArticleId(dto.getArticleId());
            apFollowBehavior.setCreatedTime(new Date());
            mongoTemplate.save(apFollowBehavior);
        }
        //返回数据
        return ResponseResult.okResult("关注完成");
    }
}
